/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.ecommerce.util.view;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author rpateixeira
 */
public class JsfUtil {
    public static void addMessage(String message){
        addMessage(null, message);
    }

    public static void addMessage(String clientId, String message){
        getFacesContext().addMessage(clientId, new FacesMessage(message));
    }

    public static void addMessage(String clientId, String message, FacesMessage.Severity severity){
        getFacesContext().addMessage(clientId, new FacesMessage(severity, message, null));
    }

    public static void addErrorMessage(String error){
        if (!getFacesContext().getPartialViewContext().getRenderIds().contains("mensagens")){
            getFacesContext().getPartialViewContext().getRenderIds().add("mensagens");
        }
        addMessage(null, error, FacesMessage.SEVERITY_ERROR);
    }

    public static void addAlertMessage(String alert){
        if (!getFacesContext().getPartialViewContext().getRenderIds().contains("mensagens")){
            getFacesContext().getPartialViewContext().getRenderIds().add("mensagens");
        }
        addMessage(null, alert, FacesMessage.SEVERITY_WARN);
    }

    public static void addSuccessMessage(String success){
        if (!getFacesContext().getPartialViewContext().getRenderIds().contains("mensagens")){
            getFacesContext().getPartialViewContext().getRenderIds().add("mensagens");
        }
        addMessage(null, success, FacesMessage.SEVERITY_INFO);
    }

    public static HttpServletRequest getRequest(){
        return (HttpServletRequest) getFacesContext().getExternalContext().getRequest();
    }

    public static HttpServletResponse getResponse(){
        return (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
    }

    public static HttpSession getSession(){
        return getRequest().getSession();
    }

    public static FacesContext getFacesContext(){
        return FacesContext.getCurrentInstance();
    }

    public static void setAtributeInSession(String key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getAtributeInSession(String key){
        return getSession().getAttribute(key);
    }

    public static Object getAtributeInRequest(String key){
        return getRequest().getAttribute(key);
    }

    public static void setAtributeInRequest(String key, Object value) {
        getRequest().setAttribute(key, value);
    }
}
